#include "ClamAVScanner.h"

namespace GPUCC
{
	bool ClamAVScanner::m_IsInitialized = false;

	bool ClamAVScanner::Init()
	{
		if (!m_IsInitialized)
		{
			m_IsInitialized = (cl_init(CL_INIT_DEFAULT) == CL_SUCCESS);
		}

		return (m_IsInitialized);
	}

	ClamAVScanner::ClamAVScanner() : m_Engine(NULL), m_NumberOfSignatures(0)
	{
	}

	ClamAVScanner::~ClamAVScanner()
	{
		if (this->m_Engine != NULL)
		{
			if (cl_engine_free(this->m_Engine) == CL_SUCCESS)
			{
				this->m_Engine = NULL;
			}
		}
	}

	bool ClamAVScanner::Init(const std::string& SignatureFolder)
	{
		this->m_Engine = cl_engine_new();

		if (this->m_Engine == NULL)
		{
			return (false);
		}

		if (cl_load(SignatureFolder.c_str(), this->m_Engine, &this->m_NumberOfSignatures, CL_DB_STDOPT) != CL_SUCCESS)
		{
			return (false);
		}

		if (cl_engine_compile(this->m_Engine) != CL_SUCCESS)
		{
			return (false);
		}

		return (true);
	}

	bool ClamAVScanner::ScanFile(const std::string& Path, ScanResult& Result)
	{
		int ScanResult;
	    const char* VirusName;

		Result.SetNotInfected();

		ScanResult = cl_scanfile(Path.c_str(), &VirusName, NULL, this->m_Engine, CL_SCAN_RAW);

		if (ScanResult == CL_VIRUS)
		{
			Result.SetInfected(VirusName);
		}

		return ((ScanResult == CL_CLEAN) || (ScanResult == CL_VIRUS));
	}
}